package rfid;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

public class RFIDCardReader {

	private static RFIDCardReader singleton; 
	
	private Socket socket;
	private SocketAddress address;
	private PrintWriter out = null;
	private BufferedReader in = null;

	private RFIDCardReader(String address) {
		socket = new Socket();
		this.address = new InetSocketAddress(address, 3333);
		connect();
	}
	
	public static RFIDCardReader createRFID() {
		if (singleton == null)
			singleton = new RFIDCardReader("localhost");
		return singleton;
	}

	
	private void connect() {
		if (!isConnected()) {
			try {
				socket.connect(address);

				out = new PrintWriter(socket.getOutputStream(), true);
				in = new BufferedReader(new InputStreamReader(socket
						.getInputStream()));

			} catch (IOException e) {
				throw new IllegalArgumentException(e.getMessage());
			}
		}
	}

	public boolean isConnected() {
		return socket.isConnected();
	}

	public String waitAndGetCard() {
		String number = null;
		try {
			connect();
			out.print("client_protocol 1\r\n");
			out.flush();
			String check = in.readLine();
			if (!check.equals("server_protocol 1.0"))
				throw new IllegalArgumentException("Wrong protocol");
			
			out.print("wait_for_card\r\n");
			out.flush();

			number = in.readLine();
			
			
			number = number.split(" ")[1];
			
			Thread.sleep(100);
			
		} catch (IOException e) {
			throw new IllegalArgumentException(e.getMessage());
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return number;
	}

	public int waitAndGetCardNumber() {
		return Integer.parseInt(waitAndGetCard());
	}
}
